package ConnectMysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Add_Delete_Insert_jdbc_Test {
	public static void main(String[] args) {
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost/huangbiao";
			String user = "root";
			String password = "root";
			con = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			System.out.println("驱动加载失败");
		}
		try {
			/*
			 * 查询数据库修改前的数据
			 */
			PreparedStatement ment1 = con.prepareStatement("select*from exam2 ");
			ResultSet set1 = ment1.executeQuery();
			System.out.println("修改前的语句为:");
			while (set1.next()) {
				System.out.print("id为" + set1.getString("id"));
				System.out.print("成绩为" + set1.getString("math"));
				System.out.print("性别为" + set1.getString("sex"));
				System.out.println("喜欢的明星为" + set1.getString("sname"));
			}
			ment1.close();
			/*
			 * 数据表添加数据
			 */
			PreparedStatement ment2 = con.prepareStatement("insert into exam2(id,math,sname) values (?,?,?)");
			ment2.setInt(1, 3435);
			ment2.setInt(2, 100);
			//ment2.setString(3, "男");
			ment2.setString(3, "黄彪");
			ment2.executeUpdate();
			ment2.close();
			/*
			 * 遍历查询数据库修改后的数据
			 */
			PreparedStatement ment3 = con.prepareStatement("select*from exam2 ");
			ResultSet set2 = ment3.executeQuery();
			System.out.println("修改后的语句为:");
			while (set2.next()) {
				System.out.print("id为" + set2.getString("id"));
				System.out.print("成绩为" + set2.getString("math"));
				System.out.print("性别为" + set2.getString("sex"));
				System.out.println("喜欢的明星为" + set2.getString("sname"));
			}
			ment3.close();
		} catch (Exception e) {
			System.out.println("连接查询数据库失败");
			e.printStackTrace();
		}

	}
}
